from django.conf import settings
from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructible
from fdfs_client.client import Fdfs_client


@deconstructible
class FastDFSStorage(Storage):
    def __init__(self, base_url=None, client_conf=None):
        if base_url is None:
            base_url = settings.FDFS_URL
        self.base_url = base_url
        if client_conf is None:
            client_conf = settings.FDFS_CLIENT_CONF
        self.client_conf = client_conf

    def _open(self, name, mode='rb'):
        pass

    def _save(self, name, content):
        client = Fdfs_client(self.client_conf)

        ret = client.upload_by_buffer(content.read())
        # {'Group name': 'group1',
        #  'Local file name': './b2c.png',
        #  'Remote file_id': 'group1/M00/00/00/wKjMg1v5EqqAUvNRAAHdP5OWzDQ155.png',
        #  'Status': 'Upload successed.',
        #  'Storage IP': '192.168.204.131',
        #  'Uploaded size': '119.00KB'}

        if ret['Status'] != 'Upload successed.':
            raise Exception('upload file failed')

        return ret['Remote file_id']

    def url(self, name):

        return self.base_url + name

    def exists(self, name):

        return False
